# encoding:utf-8
import pymysql
import json
import os

# 将所有可用的配置项写在字典里, 请使用小写字母
available_setting = {
    "proxy": "127.0.0.1:7890",  # 代理
    "mysql": None,
    "application_id": "936929561302675456",
    "guild_id": "1106931041756790784",
    "channelid": "1106931042226557022",
    "session_id": "adf61e90d9cd19b5a51d51aed5dbb58b",
    "version": "1077969938624553050",
    "id": "938956540159881230",
    "authorization": "MTEwNjA4MjQzMTM4MTAyNDc5OA.G-VMdr.MsDZ8m41FMUq2ik4imymzQhPXoQt1ha9DYI1C4",
    "flags": "--v 5",
    "is_child_thread_run": False,
    "is_site_text_secret_on": "1",
    "group_name_white_list": ["123"]
}


class Config(dict):
    def __getitem__(self, key):
        if key not in available_setting:
            raise Exception("key {} not in available_setting".format(key))
        return super().__getitem__(key)

    def __setitem__(self, key, value):
        if key not in available_setting:
            raise Exception("key {} not in available_setting".format(key))
        return super().__setitem__(key, value)

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError as e:
            return default
        except Exception as e:
            raise e


config = Config()


def load_config():
    global config
    config_path = "./config.json"
    config_str = read_file(config_path)

    # 将json字符串反序列化为dict类型
    config = Config(json.loads(config_str))

    # override config with environment variables.
    for name, value in os.environ.items():
        name = name.lower()
        if name in available_setting:
            try:
                config[name] = eval(value)
            except:
                if value == "false":
                    config[name] = False
                elif value == "true":
                    config[name] = True
                else:
                    config[name] = value

    config["mysql"] = pymysql.connect(host="数据库", port="端口", user="用户名", passwd="你的密码", db="Robot", charset="utf8mb4")


def get_root():
    return os.path.dirname(os.path.abspath(__file__))


def read_file(path):
    with open(path, mode='r', encoding='utf-8') as f:
        return f.read()


def conf():
    return config
